package com.distributor;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ActivitNewSalesAgent extends Activity
{
	
	Button btnSubmit;
	Spinner spIDProofType;
	
	
	EditText etIDNumber,etFname,etLname,
			 etEmail,etPhone1,etPhone2,etAltPhone,
			 etImei;
	Button btnBack,btnLogOut;
	Handler handler=new Handler();
	MD5Generator md5Generator=new MD5Generator();
	HttpConn httpConn=new HttpConn();
	HttpClient httpclient;
	HttpPost httppost = new HttpPost(AppData.hostURL+"/WebService/iTopUp/distributorapp.php");
	ProgressDialog pd=null;
	
	IDProofType[] idProofType; 
	String screen;
	TextView tv_FormHeader;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activit_new_salesagent);
		Bundle extras = getIntent().getExtras();
		
		if(extras.containsKey("nextscreen"))
		{
			screen=extras.getString("nextscreen");
			System.out.println("Screen:"+screen);
			tv_FormHeader= (TextView)findViewById(R.id.tv_header_resellerForm);
			tv_FormHeader.append(screen);
		}
		
		btnSubmit=(Button)findViewById(R.id.btnSubmit);
		spIDProofType=(Spinner)findViewById(R.id.sp_idProof);
		 
		btnLogOut=(Button)findViewById(R.id.btnLogout); 
	    btnBack=(Button)findViewById(R.id.btnPrevious);
	    
		etIDNumber=(EditText)findViewById(R.id.etIdNumber);
		etFname=(EditText)findViewById(R.id.etFirstName);
		etLname=(EditText)findViewById(R.id.etLastName);
		etEmail=(EditText)findViewById(R.id.etEmail);
		etPhone1=(EditText)findViewById(R.id.etPhone1);
		etPhone2=(EditText)findViewById(R.id.etPhone2);
		etAltPhone=(EditText)findViewById(R.id.etAltPhone);
		etImei=(EditText)findViewById(R.id.etIMEI);
		
		Thread thread=new Thread(getIDProofType);
		thread.start();
		
		pd=ProgressDialog.show(ActivitNewSalesAgent.this,"please wait.",null);
	    pd.setContentView(R.layout.progress);
	    btnLogOut.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				  new AlertDialog.Builder(ActivitNewSalesAgent.this)
				  .setTitle( "Exit Application" )
			      .setMessage( "Are you sure you want to Logout?" )
			      .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
			       {
			           public void onClick(DialogInterface arg0, int arg1) 
			           {
			        	   setResult(2);
			               finish();
			           }

					   public void onClick(View v) 
					   {
						 // TODO Auto-generated method stub
					   }
					   
			        })
			        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
			        {
			            public void onClick(DialogInterface arg0, int arg1)
			            {
			                //do stuff onclick of CANCEL
			            	arg0.dismiss();
			            }

						public void onClick(View v) 
						{
							// TODO Auto-generated method stub
						}
			        }).show();
		  	}
			
		 });
	    
	    btnBack.setOnClickListener(new OnClickListener() 
	    {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			finish();	
			}
		});
	    btnSubmit.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View arg0) 
			{
				// TODO Auto-generated method stub
				if(validateInput())
				{
					new Thread(createSalesAgent,"Create Sales Agent").start();
					pd=ProgressDialog.show(ActivitNewSalesAgent.this,"please wait.",null);
				    pd.setContentView(R.layout.progress); 
				}
				else
				{
					System.out.println("Validation Message:"+validateInput());
				}
			}
		});
	}
	
	boolean validateInput() 
	{
		if(etImei.getText().toString().equals("")||etImei.getText().toString().trim().length()==0)
		{
			Toast.makeText(ActivitNewSalesAgent.this,"Please Enter Reseller IMEI Number.",Toast.LENGTH_SHORT).show();
			return false;
		}
		if(etImei.getText().toString().length()<15)
		{
			Toast.makeText(ActivitNewSalesAgent.this,"IMEI Number Must be minimum of 15 Digit.",Toast.LENGTH_SHORT).show();
			return false;
		} 
		if(etPhone1.getText().toString().equals("")||etPhone1.getText().toString().trim().length()==0)
		{
			Toast.makeText(ActivitNewSalesAgent.this,"Please Enter Phone 1.",Toast.LENGTH_SHORT).show();
			return false;
		}
		if(etPhone1.getText().toString().length()<8)
		{
			Toast.makeText(ActivitNewSalesAgent.this,"Phone Number1 Must be minimum of 8 Digit.",Toast.LENGTH_SHORT).show();
			return false;
		}
		if(etPhone2.getText().toString().trim().length()>0)
	    {
			if(etPhone2.getText().toString().length()<8)
			{
				Toast.makeText(ActivitNewSalesAgent.this,"Phone Number2 Must be minimum of 8 Digit.",Toast.LENGTH_SHORT).show();
				return false;
			}
	    }
		if(etFname.getText().toString().equals("")||etFname.getText().toString().trim().length()==0)
		{
			Toast.makeText(ActivitNewSalesAgent.this,"Please Enter First Name.",Toast.LENGTH_SHORT).show();
			return false;
		}
		if(etLname.getText().toString().equals("")||etLname.getText().toString().trim().length()==0)
		{
			Toast.makeText(ActivitNewSalesAgent.this,"Please Enter Last Name.",Toast.LENGTH_SHORT).show();
			return false;
		}
		if(etEmail.getText().toString().trim().length()>0)
		{
			if(emailValidation(etEmail.getText().toString().trim())==false)
			{ 
				Toast.makeText(ActivitNewSalesAgent.this,"Enter Valid Email Address.",Toast.LENGTH_SHORT).show();
				return false;
			} 
		}  
		if(etIDNumber.getText().equals("")||etIDNumber.getText().toString().trim().length()==0)
		{
			Toast.makeText(ActivitNewSalesAgent.this,"Please Enter Reseller ID.",Toast.LENGTH_SHORT).show();
			return false;
		}
		if(etIDNumber.getText().toString().length()<4)
		{
			Toast.makeText(ActivitNewSalesAgent.this,"Reseller ID must be minimum of 4 Digit.",Toast.LENGTH_SHORT).show();
			return false;
		} 
		
		if(etAltPhone.getText().toString().trim().length()>0)
	    {
			if(etAltPhone.getText().toString().length()<8)
			{
				Toast.makeText(ActivitNewSalesAgent.this,"Alternate Phone Number2 Must be minimum of 8 Digit.",Toast.LENGTH_SHORT).show();
				return false;
			}
			else
			{
				return true;
			}
	    } 
		else
		{
			return true;
		}
		 
	}
	private boolean emailValidation(String emailstring)
	{
		Pattern emailPattern = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher emailMatcher = emailPattern.matcher(emailstring);
        
        return emailMatcher.matches();
	}
	Runnable createSalesAgent=new Runnable()
	{
		
		public void run() 
		{
			try
			{
				 
				httpclient = new DefaultHttpClient();
				System.out.println("ID Proof:"+idProofType[spIDProofType.getSelectedItemPosition()].getProofTypeName()+","+
									idProofType[spIDProofType.getSelectedItemPosition()].getProofTypeID());
			
//				System.out.println("Discount Matrix:"+resellerDiscountMatrix.get(spDiscountMatrixID.getSelectedItemPosition()).getDiscountMatrixName()+","+
//									resellerDiscountMatrix.get(spDiscountMatrixID.getSelectedItemPosition()).getDiscountMatrixID());
				//System.out.println("Acive /In Active:"+spIsActive.getSelectedItemPosition());	
				
				String checksumString=
									AppData.getUserInfo().getLoginID()+"|"+
									idProofType[spIDProofType.getSelectedItemPosition()].getProofTypeID()+"|"+
									etIDNumber.getText().toString()+"|"+ 
									etFname.getText().toString()+"|"+
									etLname.getText().toString()+"|"+
									etPhone1.getText().toString()+"|"+
									etPhone2.getText().toString()+"|"+
									etAltPhone.getText().toString()+"|"+
									etImei.getText().toString()+"|"+
									etEmail.getText().toString()+"|"+
									AppData.getUserInfo().getpublickey();
				System.out.println("Check sum string===>"+checksumString);
				String finalChecksum = md5Generator.MD5(md5Generator.SHA1(checksumString));
				System.out.println("Final Checksum:"+finalChecksum);
				
				//creating Post Request for reseller creation WSDL
				try 
				{     
					
					   //function=ResellerCreation&LoginId=565m9t7b&ResellerName=Fgvfdv&IDProofTypeID=1&IDNumber=444444444&ResellerCategoryID=1&FName=Jknjrnfknsrjkvf4&LName=Frfreer&Phone1=444444444433434&Phone2=4454534563463434&AltPhone=45435345345345&IMEI=4353454354354543&Email=gdg@d.com&Address1=Effrvtrgtgtr&Address2=Rtytrytrytr&AreaName=Trhthy&AreaZipCode=89898989&CountryStateID=1414&IsActive=0&DiscountMatrixID=7&Checksum=7d0a9fc08edcdd59d183845b8cf2a423
						
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
						nameValuePairs.add(new BasicNameValuePair("function", "CreateSubAccount"));
					    nameValuePairs.add(new BasicNameValuePair("LoginId", AppData.getUserInfo().getLoginID())); 
					    nameValuePairs.add(new BasicNameValuePair("IDProofTypeID",idProofType[spIDProofType.getSelectedItemPosition()].getProofTypeID()));
					    nameValuePairs.add(new BasicNameValuePair("IDNumber", etIDNumber.getText().toString())); 
					    nameValuePairs.add(new BasicNameValuePair("FName",etFname.getText().toString() ));
					    nameValuePairs.add(new BasicNameValuePair("LName", etLname.getText().toString()));
					    nameValuePairs.add(new BasicNameValuePair("Phone1",etPhone1.getText().toString()));
					    nameValuePairs.add(new BasicNameValuePair("Phone2",etPhone2.getText().toString()));
					    nameValuePairs.add(new BasicNameValuePair("AltPhone", etAltPhone.getText().toString()));
					    nameValuePairs.add(new BasicNameValuePair("IMEI",etImei.getText().toString()));
					    nameValuePairs.add(new BasicNameValuePair("Email", etEmail.getText().toString()));
					    nameValuePairs.add(new BasicNameValuePair("Checksum",finalChecksum)); 
					    
					    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					    
					    ResponseHandler<String> responseHandler = new BasicResponseHandler();
					    
						String response = httpclient.execute(httppost,responseHandler);
						System.out.println("Response:"+response);
					    
						  final JSONObject jsonObject=new JSONObject(response);
						
						  if(jsonObject.getString("ResponseCode").equals("000"))
			              {
							  	handler.post(new Runnable()
								{ 
									public void run() 
									{
										// TODO Auto-generated method stub
										pd.dismiss();
										Toast.makeText(ActivitNewSalesAgent.this,"Reseller Created Successfully",Toast.LENGTH_LONG).show();
										finish();
										 
/*										Intent i=new Intent(ActivitNewSalesAgent.this,ActivityMenu.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(i);
*/									}
								});
			              }
						  else
						  {
							  handler.post(new Runnable()
			            	  {
								
								public void run() 
								{
									// TODO Auto-generated method stub
									pd.dismiss();
									try 
									{
										Toast.makeText(ActivitNewSalesAgent.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
										
									}
									catch (JSONException e) 
									{
										e.printStackTrace();
									}
								}
							});
							  
						  }
						
						
						
				} 
				catch (final JSONException e)
				{
					handler.post(new Runnable()
					{
						
						public void run() 
						{
							// TODO Auto-generated method stub
							pd.dismiss();
							Toast.makeText(ActivitNewSalesAgent.this,e.getMessage(),Toast.LENGTH_LONG).show(); 
						}
					});
				}
				catch(UnknownHostException e)
				{
					
					handler.post(new Runnable()
					{
						
						public void run() 
						{
							// TODO Auto-generated method stub
							pd.dismiss();
							Toast.makeText(ActivitNewSalesAgent.this,getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
						}
					});
					 
				}
				catch (final ClientProtocolException e) 
				{
			        // TODO Auto-generated catch block
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(ActivitNewSalesAgent.this,getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
							}
						});
						 
			    }
				
				catch (final IOException e) 
				{
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(ActivitNewSalesAgent.this, e.getMessage(),Toast.LENGTH_LONG).show();
							}
						}); 
			    }  
				  
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		  
		}
	};
	
	Runnable getIDProofType =new Runnable()
	{
		
		public void run() 
		{
			try
			{
			  String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+
					 	AppData.getUserInfo().getpublickey() ));
			  String URL=AppData.hostURL+"/WebService/iTopUp/distributorapp.php/ProofType/LoginId/"+AppData.getUserInfo().getLoginID()
					  +"/Checksum/"+checksum;
			  System.out.println("URL===>\n"+URL);
			  String response=httpConn.createHttpConn(URL);
			  System.out.println("Result:"+response); 
			  
			 
			  final JSONObject jsonObject=new JSONObject(response);
			  JSONArray jsonArray;
			  
			  	if(jsonObject.getString("ResponseCode").equals("000"))
			  	{
			  		 ArrayList<String> id=new ArrayList<String>();
					 ArrayList<String> name=new ArrayList<String>();
					 jsonArray=jsonObject.getJSONArray("IDProofTypeID");
					 idProofType=new IDProofType[jsonArray.length()];
					 
					 for(int i=0;i<jsonArray.length();i++)
					 {
						 id.add(jsonArray.getString(i));
					 } 
					 jsonArray=jsonObject.getJSONArray("IDProofTypeName");
					 
					 for(int i=0;i<jsonArray.length();i++)
					 {
						 name.add(jsonArray.getString(i));
					 }
					 
					 for(int i=0;i<id.size();i++)
					 {
						idProofType[i]=new IDProofType();
						idProofType[i].setProofTypeID(id.get(i));
						idProofType[i].setProofTypeName(name.get(i));
						
						System.out.println(i+"ID:"+idProofType[i].getProofTypeID());
						System.out.println(" Name:"+idProofType[i].getProofTypeName());
						
					 }
					 handler.post(new Runnable()
					 {
						
						public void run() 
						{
							String[] str=new String[idProofType.length];
							for(int i=0;i<idProofType.length;i++)
							{
								str[i]=idProofType[i].getProofTypeName();
								System.out.println(str[i]);
							}
							
							ArrayAdapter<String> spAdapter= new ArrayAdapter<String>(ActivitNewSalesAgent.this, R.layout.simple_spinner_item,str);
							spAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
							spIDProofType.setAdapter(spAdapter);
							
							pd.dismiss();
						}
					});
					 
					
			  	}
			  	else
			  	{
			  		handler.post(new Runnable()
	            	  {
						
						public void run() 
						{
							// TODO Auto-generated method stub
							pd.dismiss();
							try 
							{
								Toast.makeText(ActivitNewSalesAgent.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
								startActivity(new Intent(ActivitNewSalesAgent.this,ActivityMenu.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
			  	}
			  
			   
			}
			catch(final Exception e)
			{
				handler.post(new Runnable()
          	  {
					
					public void run() 
					{
						// TODO Auto-generated method stub
						pd.dismiss();
						Toast.makeText(ActivitNewSalesAgent.this,e.getMessage(),Toast.LENGTH_SHORT).show();
						startActivity(new Intent(ActivitNewSalesAgent.this,ActivityMenu.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
						 
					}
				});
			}
			  
		}
	};
	private class IDProofType 
	{
		public IDProofType() {
			// TODO Auto-generated constructor stub
		}
		private String proofTypeID,proofTypeName;

		public String getProofTypeID() 
		{
			return proofTypeID;
		}

		public void setProofTypeID(String proofTypeID) 
		{
			this.proofTypeID = proofTypeID;
		}

		public String getProofTypeName() 
		{
			return proofTypeName;
		}

		public void setProofTypeName(String proofTypeName) 
		{
			this.proofTypeName = proofTypeName;
		}
		
	}
}
